package com.elvin.platform.socketIO;

import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;

//@Component
public class MessageEventHandler {

  public static SocketIOServer socketIoServer;
  static ArrayList<UUID> listClient = new ArrayList<>();
  static final int limitSeconds = 60;

  @Autowired
  public MessageEventHandler(SocketIOServer server) {
    this.socketIoServer = server;
  }


  @OnConnect
  public void onConnect(SocketIOClient client) {
    listClient.add(client.getSessionId());
    System.out.println("客户端:" + client.getSessionId() + "已连接");
  }


  @OnDisconnect
  public void onDisconnect(SocketIOClient client) {
    System.out.println("客户端:" + client.getSessionId() + "断开连接");
  }


  @OnEvent(value = "msg")
  public void onEvent(SocketIOClient client, String msg) {
    System.out.println("客户端发来的消息：" + msg);
    socketIoServer.getClient(client.getSessionId()).sendEvent("msg", "确认客户端接收到消息了");
    sendClientEvent();
  }


  public void sendClientEvent() {   //这里就是向客户端推消息了
    String dateTime = Long.toString(new Date().getTime());
    System.out.println("客户端个数："+listClient.size());
    for (UUID clientId : listClient) {
      if (socketIoServer.getClient(clientId) == null) continue;
      socketIoServer.getClient(clientId).sendEvent("res", "向客户端推送消息！");

    }
  }


}
